package cn.bocweb.spinning.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.DelFavoritesBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.GetCollectFavoritesBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.activity.InfoDetailActivity;
import cn.bocweb.spinning.view.adapter.CollectInfoAdapter;
import cn.bocweb.spinning.view.common.BaseView;
import cn.bocweb.spinning.view.common.SwipeRefreshHelper;
import cn.bocweb.spinning.view.dialog.LoadingDialog;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 15/12/21.
 */
public class CollectInfoFragment extends Fragment implements BaseView, View.OnClickListener {

    CollectInfoAdapter adapter;
    UserPresenter presenter;

    List<GetCollectFavoritesBean.DataEntity> list;
    @Bind(R.id.collect_info_listview)
    ListView collectInfoListview;
    @Bind(R.id.collect_info_refresh)
    SwipeRefreshLayout collectInfoRefresh;

    LoadingDialog dialog;
    SwipeRefreshHelper helper;

    int page = 1;
    @Bind(R.id.my_collect_delete_all)
    CheckBox myCollectDeleteAll;
    @Bind(R.id.my_collect_delete_btn)
    Button myCollectDeleteBtn;
    @Bind(R.id.my_collect_delete_all_layout)
    RelativeLayout myCollectDeleteAllLayout;
    List<Integer> aidList;
    String userid;
    boolean isLastPage = false;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_collect_info, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        dialog = new LoadingDialog(getActivity());

        initList();
        initModel();
        initClickBtn();
    }

    private void initClickBtn() {
        myCollectDeleteBtn.setOnClickListener(this);
    }

    private void initModel() {

        aidList = new ArrayList<>();

        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(getActivity());
        userid = user.getUserid();

        presenter = new UserPresenterImp();
        presenter.getCollectFavorites(user.getUserid(), page, null);
        showLoading();
    }

    private void initList() {
        list = new ArrayList<>();
        adapter = new CollectInfoAdapter(getActivity(), list, myCollectDeleteAll);

        collectInfoListview.setAdapter(adapter);
        collectInfoListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), InfoDetailActivity.class);
                intent.putExtra(Constant.INFO_DETAIL, list.get(position).getAid());
                startActivity(intent);
            }
        });
        collectInfoRefresh.setColorSchemeResources(R.color.colorPrimary);
        helper = new SwipeRefreshHelper(collectInfoRefresh, collectInfoListview, new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                list.clear();
                adapter.notifyDataSetChanged();
                presenter.getCollectFavorites(userid, page, null);
                isLastPage = false;
            }

            @Override
            public void onLoad() {
                if (!isLastPage) {
                    page ++;
                    presenter.getCollectFavorites(userid, page, null);
                } else {
                    DeviceUtil.MyToast(getActivity(), "已经是最后一页");
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void onEventMainThread(GetCollectFavoritesBean bean) {
        if (collectInfoRefresh.isRefreshing()) {
            collectInfoRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData().size() > 0) {
                list.addAll(bean.getData());
                DeviceUtil.Log(list.get(0).getAid());
                adapter.notifyDataSetChanged();
            }
        } else if (bean.getReturn_code() == -203) {
            DeviceUtil.MyToast(getActivity(), "已经是最后一页");
            isLastPage = true;
        } else {
            DeviceUtil.MyToast(getActivity(), bean.getMsg());
        }
        hideLoading();
    }

    public void onEventMainThread(DelFavoritesBean bean) {
        DeviceUtil.MyToast(getActivity(), bean.getMsg());
        if (bean.getReturn_code() == 0) {
            int p = 0;
            for (int i : aidList) {
                i -= p;
                list.remove(i);
                p++;
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        if (collectInfoRefresh.isRefreshing()) {
            collectInfoRefresh.setRefreshing(false);
        }

        hideLoading();
        DeviceUtil.MyToast(getActivity(), bean.getErrorMsg());
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }

    public void deleteAdapter() {
        adapter.setShowSelect(true);
        adapter.notifyDataSetChanged();

        myCollectDeleteAllLayout.setVisibility(View.VISIBLE);
        myCollectDeleteAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    adapter.setSetAllSelect(true);
                    adapter.notifyDataSetChanged();
                } else if (adapter.isSetAllSelect()) {
                    adapter.setSetAllSelect(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    public void clearAdapter() {
        adapter.setShowSelect(false);
        adapter.setSetAllSelect(false);
        adapter.notifyDataSetChanged();
        myCollectDeleteAll.setChecked(false);
        myCollectDeleteAllLayout.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_collect_delete_btn: {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.insert(0, "[");
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(getActivity());
                for (int i = 0; i < list.size(); i++) {
                    if (adapter.getMap().containsKey(i)) {
                        if (adapter.map.get(i)) {
                            stringBuffer.append(list.get(i).getAid() + ",");
                            aidList.add(i);
                        }
                    }
                }
                stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
                stringBuffer.append("]");
                presenter.delFavorites(stringBuffer.toString(), dataEntity.getUserid());
                break;
            }
        }
    }


}
